import { ElementPropertyConfig } from '@farris/ide-property-panel';
import { EditorTypes } from '@farris/ui-datagrid-editors';
import { DesignerEnvType, FormSchemaEntityFieldType$Type, UniformEditorDataUtil } from '@farris/designer-services';
import { ItemCollectionConverter, ItemCollectionEditorComponent } from '@farris/designer-devkit';
import { FormPropertyChangeObject } from '../../../../entity/property-change-entity';
import { InputProps } from '../../common/property/input-property-config';

export class RadioGroupProp extends InputProps {

    propertyConfig: ElementPropertyConfig[];

    getPropConfig(propertyData: any): ElementPropertyConfig[] {
        this.propertyConfig = [];

        // 基本信息属性
        const basicPropConfig = this.getBasicPropConfig(propertyData, this.viewModelId);
        this.propertyConfig.push(basicPropConfig);

        // 外观属性
        const appearanceProperties = this.getAppearancePropConfig(propertyData, this.viewModelId);
        this.propertyConfig.push(appearanceProperties);

        // 行为属性
        const behaviorPropConfig = this.getBehaviorPropConfig(propertyData, this.viewModelId);
        this.propertyConfig.push(behaviorPropConfig);

        // 表达式属性
        const exprPropConfig = this.getExpressionPropConfig(propertyData, this.viewModelId);
        if (exprPropConfig) {
            this.propertyConfig.push(exprPropConfig);
        }
        // 事件属性
        const eventPropConfig = this.getEventPropertyConfig(propertyData, this.viewModelId);
        this.propertyConfig.push(eventPropConfig);

        return this.propertyConfig;

    }


    /**
     * 外观属性
     */
    private getAppearancePropConfig(propertyData: any, viewModelId: string, showPosition = 'card'): ElementPropertyConfig {
        const self = this;

        let appearanceProperties = [];
        if (showPosition === 'card') {
            const commonProps = this.getAppearanceCommonPropConfig(propertyData, viewModelId);
            appearanceProperties = appearanceProperties.concat(commonProps);
        }

        appearanceProperties.push(
            {
                propertyID: 'isHorizontal',
                propertyName: '水平布局',
                propertyType: 'boolean',
                description: '是否水平布局'
            }
        );
        const config = {
            categoryId: 'appearance',
            categoryName: '外观',
            properties: appearanceProperties,
            setPropertyRelates(changeObject: FormPropertyChangeObject, prop, parameters) {

                if (!changeObject) {
                    return;
                }
                self.changeAppearancePropertyRelates(this.properties, changeObject, propertyData, parameters);
            }

        };

        if (showPosition !== 'card') {
            Object.assign(config, {
                categoryId: showPosition + '_' + config.categoryId,
                propertyData,
                enableCascade: true,
                parentPropertyID: 'editor',
                tabId: showPosition,
                tabName: '编辑器'
            });
        }
        return config;
    }

    /**
     * 行为属性
     */
    private getBehaviorPropConfig(propertyData: any, viewModelId: string, showPosition = 'card'): ElementPropertyConfig {
        const enumDataConfig = this.getEnumDataConfig(propertyData, viewModelId);
        const behaviorProperties = this.getBehaviorCommonPropConfig(propertyData, viewModelId);

        behaviorProperties.push(
            {
                propertyID: 'dataSourceType',
                propertyName: '数据源类型',
                propertyType: 'select',
                description: '数据源类型选择',
                iterator: [{ key: 'static', value: '静态' }, { key: 'dynamic', value: '动态' }],
                defaultValue: 'static'
            },
            {
                propertyID: 'enumData',
                propertyName: '枚举数据',
                propertyType: 'modal',
                description: '枚举数据设置',
                editor: ItemCollectionEditorComponent,
                converter: new ItemCollectionConverter(),
                ...enumDataConfig.editorConfig,
                visible: propertyData.dataSourceType === 'static'
            },
            {
                propertyID: 'bindDataSource',
                propertyName: '绑定数据源',
                propertyType: 'unity',
                description: '绑定数据源设置',
                editorParams: {
                    controlName: UniformEditorDataUtil.getControlName(propertyData),
                    editorOptions: {
                        types: ['variable'],
                        variables: UniformEditorDataUtil.getVariables(viewModelId, this.domService),
                        getVariables: () => UniformEditorDataUtil.getVariables(viewModelId, this.domService),
                        newVariableType: 'Array',
                        newVariablePrefix: ''
                    }
                },
                visible: propertyData.dataSourceType === 'dynamic',
            },
            {
                propertyID: 'valueField',
                propertyName: '枚举值字段',
                propertyType: 'string',
                description: '枚举值字段设置',
                readonly: propertyData.dataSourceType === 'static',
            },
            {
                propertyID: 'textField',
                propertyName: '枚举名称字段',
                propertyType: 'string',
                description: '枚举名称字段设置',
                readonly: propertyData.dataSourceType === 'static',
            }
        );

        const self = this;
        const config = {
            categoryId: 'behavior',
            categoryName: '行为',
            properties: behaviorProperties,
            setPropertyRelates(changeObject: FormPropertyChangeObject, data, parameters) {
                if (!changeObject) {
                    return;
                }
                self.changeBehaviorPropertyRelates(this.properties, changeObject, propertyData, parameters, showPosition);

                switch (changeObject && changeObject.propertyID) {
                    case 'dataSourceType': {
                        const enumData = this.properties.find(p => p.propertyID === 'enumData');
                        const bindDataSource = this.properties.find(p => p.propertyID === 'bindDataSource');
                        const valueField = this.properties.find(p => p.propertyID === 'valueField');
                        const textField = this.properties.find(p => p.propertyID === 'textField');

                        if (enumData) {
                            enumData.visible = changeObject.propertyValue === 'static';
                        }
                        if (bindDataSource) {
                            bindDataSource.visible = changeObject.propertyValue !== 'static';
                        }
                        if (valueField) {
                            valueField.readonly = changeObject.propertyValue === 'static';
                        }
                        if (textField) {
                            textField.readonly = changeObject.propertyValue === 'static';
                        }


                        break;
                    }
                    case 'enumData': {
                        if (enumDataConfig.dynamicMappingKeys && parameters) {
                            propertyData.valueField = parameters.valueField;
                            propertyData.textField = parameters.nameField;
                        }
                        changeObject.relateChangeProps = [{
                            propertyID: 'valueField',
                            propertyValue: propertyData.valueField
                        },
                        {
                            propertyID: 'textField',
                            propertyValue: propertyData.textField
                        }];
                        break;
                    }

                }
            }

        };

        if (showPosition !== 'card') {
            Object.assign(config, {
                categoryId: showPosition + '_' + config.categoryId,
                propertyData,
                enableCascade: true,
                parentPropertyID: 'editor',
                tabId: showPosition,
                tabName: '编辑器'
            });
        }
        return config;
    }


    /**
     * 枚举数据的编辑器不同：
     * kendo的控件确定只有value-name键值
     * farris的控件若绑定了枚举字段只有value-name 键值；若绑定了变量或者字符串字段则可以自行指定idField 和textField
     */
    getEnumDataConfig(propertyData: any, viewModelId: string): { editorConfig: any, dynamicMappingKeys: boolean } {
        if (!propertyData.binding) {
            return { editorConfig: null, dynamicMappingKeys: false };
        }

        const editorConfig: any = {
            editorParams: {
                columns: [
                    { field: 'value', title: '枚举值', editor: { type: EditorTypes.TEXTBOX } },
                    { field: 'name', title: '枚举名称', editor: { type: EditorTypes.TEXTBOX } },
                ],
                requiredFields: ['value', 'name'],
                uniqueFields: ['value', 'name'],
                modalTitle: '枚举编辑器',
                canEmpty: false
            }
        };
        // 判断枚举数据是否只读
        editorConfig.editorParams.readonly = this.checkEnumDataReadonly(propertyData, viewModelId);

        // 绑定枚举字段的 下拉控件，编辑器只支持value-name
        if (propertyData.binding.type === 'Form') {
            const dgVM = this.dgVMService.getDgViewModel(viewModelId);
            const dgVMField = dgVM.fields.find(f => f.id === propertyData.binding.field);
            if (dgVMField.type.name === 'Enum') {
                return { editorConfig, dynamicMappingKeys: false };
            }
        }
        editorConfig.editorParams.dynamicMappingKeys = true;
        editorConfig.editorParams.valueField = propertyData.valueField;
        editorConfig.editorParams.nameField = propertyData.textField;

        return { editorConfig, dynamicMappingKeys: true };
    }



    /**
     * 判断枚举数据是否只读：运行时定制环境中的下拉框若绑定基础表单的枚举字段，则不可新增、删除、修改枚举值
     * @param propertyData 下拉框控件属性值
     * @param viewModelId 控件所在视图模型id
     */
    private checkEnumDataReadonly(propertyData: any, viewModelId: string): boolean {
        if (this.formBasicService.envType !== DesignerEnvType.runtimeCustom) {
            return false;
        }
        // 没有绑定信息或者绑定变量
        if (!propertyData.binding || propertyData.binding.type !== 'Form') {
            return false;
        }

        const fieldInfo = this.schemaService.getFieldByIDAndVMID(propertyData.binding.field, viewModelId);
        if (fieldInfo && fieldInfo.schemaField && fieldInfo.schemaField.type &&
            fieldInfo.schemaField.type.$type === FormSchemaEntityFieldType$Type.EnumType) {
            const code = fieldInfo.schemaField.code;
            const label = fieldInfo.schemaField.label;

            // 扩展字段label的规则：'ext_' + code + '_Lv9'，不符合规则的字段认为是基础表单字段
            if (label !== 'ext_' + code + '_Lv9') {
                return true;
            }
        }

        return false;
    }

    /**
     * table单元格编辑器属性
     * @param tdData 单元格数据
     * @param viewModelId viewModelId
     * @returns 属性配置
     */
    getTableTdEdtiorPropConfig(tdData: any, viewModelId: string): ElementPropertyConfig[] {
        const propertyData = tdData.editor;

        this.propertyConfig = [];

        // 外观属性
        const appearanceConfig = this.getAppearancePropConfig(propertyData, viewModelId, 'tableTdEditor');
        this.propertyConfig.push(appearanceConfig);

        // 行为属性
        const behaviorConfig = this.getBehaviorPropConfig(propertyData, viewModelId, 'tableTdEditor');
        behaviorConfig.properties = behaviorConfig.properties.filter(p => !'binding,visible'.includes(p.propertyID));
        this.propertyConfig.push(behaviorConfig);


        // 表达式属性
        const exprPropConfig = this.getExpressionPropConfig(propertyData, viewModelId, 'tableTdEditor');
        if (exprPropConfig) {
            this.propertyConfig.push(exprPropConfig);
        }

        // 事件属性
        const eventPropConfig = this.getEventPropertyConfig(propertyData, this.viewModelId, 'tableTdEditor');
        this.propertyConfig.push(eventPropConfig);

        return this.propertyConfig;
    }

}
